package com.qf.shiro2202day02.shiroconfig;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){

        final DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();

        //1 免登录的url

        chainDefinition.addPathDefinition("/register.html","anon");
        chainDefinition.addPathDefinition("/favicon.ico","anon");

        // 放行登录接口
        chainDefinition.addPathDefinition("/user/login","anon");
        chainDefinition.addPathDefinition("/login","anon");
        // 放行注册接口
        chainDefinition.addPathDefinition("/user/register","anon");

        chainDefinition.addPathDefinition("/getuser","anon");


        // 放行报错接口
        chainDefinition.addPathDefinition("/error","anon");


        // 设置免登录cookie可以访问的的url
        chainDefinition.addPathDefinition("/home.html","user");

        //2 需要登录的url
        chainDefinition.addPathDefinition("/**","authc");



        return chainDefinition;
    }

    @Bean
    public Realm customRealm(){
        final CustomRealm customRealm = new CustomRealm();

        // 密码匹配器对象
        final HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();

        credentialsMatcher.setHashAlgorithmName("md5");  // 算法名

        credentialsMatcher.setHashIterations(1024);  // hash次数

        // 设置加密方式
        customRealm.setCredentialsMatcher(credentialsMatcher);

        // 整合缓存配置
        customRealm.setCacheManager(new EhCacheManager());
        // 开启缓存
        customRealm.setCachingEnabled(true);
        // 开启身份认证缓存
        customRealm.setAuthenticationCachingEnabled(true);
        // 开启授权数据缓存
        customRealm.setAuthorizationCachingEnabled(true);


        return customRealm;
    }


}
